package com.bjsdzk.collector.one2one;

import com.alibaba.dubbo.config.*;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSONObject;
import com.bjsdzk.backend.rpc.APPService;
import com.bjsdzk.backend.rpc.CollectorService;
import com.bjsdzk.backend.rpc.PhtService;
import com.bjsdzk.backend.rpc.Platform2Service;
import com.bjsdzk.collector.constant.Constant;
import com.bjsdzk.collector.controller.TelecomController;
import com.bjsdzk.collector.entity.DelayedList;
import com.bjsdzk.collector.entity.model.Command;
import com.bjsdzk.collector.mapper.CommandMapper;
import com.bjsdzk.collector.rpc.MockPlatformServiceImpl;
import com.bjsdzk.collector.timer.MyJob;
import com.bjsdzk.collector.utils.PropertyUtil;
import com.bjsdzk.collector.utils.TimeUtil;
import com.bjsdzk.collector.utils.Utils;
import com.bjsdzk.collector.utils.TimeUtil.TimeFormat;

import io.vertx.core.AsyncResult;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.file.FileSystem;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.redis.RedisClient;
import io.vertx.redis.RedisOptions;
import io.vertx.redis.op.ScanOptions;

import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.PostConstruct;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;


/**
 * Created by zealdin on 2018/1/9.
 */
@Component
public class HostServer implements CommandLineRunner {

    @Autowired
    private Environment env;
    @Autowired
    private Vertx vertx;
    @Value("${spring.profiles.active}")
    private String profile;

    @Reference(check = false, version = "1.0.0", lazy = true, mock = "com.bjsdzk.collector.rpc.MockPlatformServiceImpl")
    private Platform2Service platform2Service;
    @Reference(check = false, version = "1.0.0", lazy = true)
    private PhtService phtService;
    @Reference(check = false, version = "1.0.0", lazy = true, mock = "com.bjsdzk.collector.rpc.MockAppService")
    private APPService aPPService;
    @Reference(check = false, version = "2.0.0", lazy = true, mock = "com.bjsdzk.collector.rpc.MockAppService")
    private APPService aPPService2;


    private static volatile boolean sendFlag;
    private static Map<Integer, Queue<String>> mapCmd = new ConcurrentHashMap<>();

    private static CommandMapper commandMapper;

    private static Map<String, Object> readMap = new ConcurrentHashMap<>();
    @Autowired
    private CommandMapper commandMapper2;
    @Autowired
    private RedisClient redis;

    @PostConstruct
    public void beforeInit() {
        commandMapper = commandMapper2;
    }

    private static Logger logger = LoggerFactory.getLogger(HostServer.class);

    public static final  String  YRWGDATA="YRWGDATA";

    @Override
    public void run(String... args) throws Exception {
//    	VertxOptions options = new VertxOptions();
//    	options.setMaxEventLoopExecuteTime(Long.MAX_VALUE);
//    	options.setWorkerPoolSize(1000);
//        Vertx vertx = Vertx.vertx(options);

        EventBus eventBus = vertx.eventBus();

//        MqttClient client = MqttClient.create(vertx);
//        RedisOptions config = new RedisOptions()
//                .setHost(env.getProperty("spring.redis.host"));
//        
//        RedisClient redis = RedisClient.create(vertx, config);

        logger.info("properties文件内容：spring.redis.host:" + env.getProperty("spring.redis.host") + "==>mongoDBAddress:" + env.getProperty("spring.data.mongodb.uri") + "==>fifteenMinutesFlag:" + env.getProperty("fifteenMinutesFlag"));

        CountDownLatch countDownLatch = new CountDownLatch(1);
        LocalDateTime plusHours = LocalDateTime.now().plusHours(1);
        JsonArray keysAll = new JsonArray();
        DelayQueue<DelayedList> queue = new DelayQueue<>();
        List<Integer> list = new ArrayList<>();
        long lon = 1000;
        queue.clear();
        list.add(1);

        redis.keys("port_*", res -> {
            if (res.succeeded()) {
                keysAll.addAll(res.result());
                countDownLatch.countDown();
            }
        });
        countDownLatch.await();

        keysAll.forEach(a -> {

            redis.get(a.toString(), res -> {
                if (res.succeeded()) {

                    if (res.result().contains("_")) {
                        queue.offer(new DelayedList(list.get(0), a.toString() + "_&" + res.result(), lon * list.get(0)));
                    } else {
                        queue.offer(new DelayedList(list.get(0), a.toString(), lon * list.get(0)));
                    }
                    list.set(0, list.get(0) + 1);

                }
            });
        });


        try {
            //得到默认的调度器
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

            //定义当前调度器的具体作业对象
            JobDetail job = newJob(MyJob.class)
                    .withIdentity("job", "group")
                    .build();

            job.getJobDataMap().put("eventbus", eventBus);

            //作业的触发器
            Trigger trigger = newTrigger()
                    .withIdentity("trigger1", "group1")
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule("0 0/15 * * * ?")) //在任务调度器中，使用任务调度器的 CronScheduleBuilder 来生成一个具体的 CronTrigger 对象
                    .build();
            //注册作业和触发器
            if (!scheduler.checkExists(job.getKey())) {
                scheduler.scheduleJob(job, trigger);
            }

            //开始调度任务
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        // 当前应用配置
        ApplicationConfig application = new ApplicationConfig();
        application.setName("collector-2.0");
//        application.setQosEnable(false);

        // 连接注册中心配置
        RegistryConfig registry = new RegistryConfig();
        registry.setAddress(env.getProperty("spring.dubbo.registry.address"));
//        registry.setUsername("aaa");
//        registry.setPassword("bbb");

        // 服务提供者协议配置
        ProtocolConfig protocol = new ProtocolConfig();
        protocol.setName("dubbo");
        protocol.setPort(9901);
        protocol.setThreads(200);
//        protocol.setHost("192.168.1.11");

        CollectorService collectorService = new CollectorServiceImpl(vertx, eventBus, redis,platform2Service);

        // 服务提供者暴露服务配置
        ServiceConfig<CollectorService> service = new ServiceConfig<>(); // 此实例很重，封装了与注册中心的连接，请自行缓存，否则可能造成内存和连接泄漏
        service.setApplication(application);
        service.setRegistry(registry); // 多个注册中心可以用setRegistries()
        service.setProtocol(protocol); // 多个协议可以用setProtocols()
        service.setInterface(CollectorService.class);
        service.setRef(collectorService);
        service.setTimeout(30000);
        service.setAsync(false);
        service.setVersion("1.0.0");

        // 暴露及注册服务
        service.export();

//        // 引用远程服务
//        ReferenceConfig<Platform2Service> reference = new ReferenceConfig<>(); // 此实例很重，封装了与注册中心的连接以及与提供者的连接，请自行缓存，否则可能造成内存和连接泄漏
//        reference.setApplication(application);
//        reference.setRegistry(registry); // 多个注册中心可以用setRegistries()
//        reference.setInterface(Platform2Service.class);
//        reference.setCheck(false);
//        reference.setTimeout(30000);
//        reference.setRetries(3);
//        reference.setAsync(false);
//        reference.setVersion("1.0.0");
//
//
//        // 和本地bean一样使用xxxService
//        Platform2Service platform2Service = reference.get();
//
//        ReferenceConfig<PhtService> reference2 = new ReferenceConfig<>(); // 此实例很重，封装了与注册中心的连接以及与提供者的连接，请自行缓存，否则可能造成内存和连接泄漏
//        reference2.setApplication(application);
//        reference2.setRegistry(registry); // 多个注册中心可以用setRegistries()
//        reference2.setInterface(PhtService.class);
//        reference2.setCheck(false);
//        reference2.setTimeout(30000);
//        reference2.setAsync(false);
//        reference2.setVersion("1.0.0");
//        
//
//        // 和本地bean一样使用xxxService
//        PhtService phtService = reference2.get();

        ExecutorService fixedThreadPool = Executors.newCachedThreadPool();
        // 断开连接事件
        eventBus.consumer("connector.add", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            if (platform == 1) {
                invokeRpc((t) -> {
                    platform2Service.deviceAdd(msg.body().toString());
                });
            } else if (platform == 3) {
                invokeRpc((t) -> {
                    phtService.deviceAdd(msg.body().toString());
                });
            }

        });

        // 断开连接事件
        eventBus.consumer("connector.status", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            Integer port = new JsonObject(msg.body().toString()).getInteger("port");
            Integer status = new JsonObject(msg.body().toString()).getInteger("status");
            if (status == 0) {
                logger.info("==>port:" + port + "==>platform:" + platform + "==>" + "downLine：" + msg.body().toString());
            }

            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    if (platform == 1) {
                        invokeRpc((t) -> {
                            platform2Service.statusChange(msg.body().toString());
                        });
                    } else if (platform == 3) {
                        invokeRpc((t) -> {
                            phtService.statusChange(msg.body().toString());
                        });
                    }
                }
            });
        });

        // 开始采集事件
        eventBus.consumer("connector.start", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            if (platform == 1) {
                invokeRpc((t) -> {
                    platform2Service.deviceStart(msg.body().toString());
                });
            } else if (platform == 3) {
                invokeRpc((t) -> {
                    phtService.deviceStart(msg.body().toString());
                });
            }
        });

        // 停止采集事件
        eventBus.consumer("connector.stop", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            if (platform == 1) {
                invokeRpc((t) -> {
                    platform2Service.deviceStop(msg.body().toString());
                });
            } else if (platform == 3) {
                invokeRpc((t) -> {
                    phtService.deviceStop(msg.body().toString());
                });
            }
        });

        // 超过预警阈值
        eventBus.consumer("connector.data.warn", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            if (platform == 1) {
                invokeRpc((t) -> {
                    platform2Service.warn(msg.body().toString());
                });
            } else if (platform == 3) {
                invokeRpc((t) -> {
                    phtService.warn(msg.body().toString());
                });
            }
        });

        // 超过告警阈值
        eventBus.consumer("connector.data.error", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            Integer port = new JsonObject(msg.body().toString()).getInteger("port");
            logger.info("==>port:" + port + "==>platform:" + platform + "==>" + "errorData：" + msg.body().toString());
            if (platform == 1) {
                invokeRpc((t) -> {
                    platform2Service.error(msg.body().toString());
                });
            } else if (platform == 3) {
                invokeRpc((t) -> {
                    phtService.error(msg.body().toString());
                });
            }
        });

        // 故障
        eventBus.consumer("connector.data.fault", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            logger.info("故障数据：" + msg.body().toString());
            if (platform == 1) {
                invokeRpc((t) -> {
                    platform2Service.fault(msg.body().toString());
                });
            } else if (platform == 3) {
                invokeRpc((t) -> {
                    phtService.fault(msg.body().toString());
                });
            }
        });

        eventBus.consumer("connector.data.faultChannel", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            logger.info("485故障数据：" + msg.body().toString());
            if (platform == 1) {
                invokeRpc((t) -> {
                    platform2Service.faultChannel(msg.body().toString());
                });
            } else if (platform == 3) {
                invokeRpc((t) -> {
                    phtService.faultChannel(msg.body().toString());
                });
            }
        });

        eventBus.consumer("connector.data.faultDevice", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            logger.info("故障数据：" + msg.body().toString());
            if (platform == 1) {

                invokeRpc((t) -> {
                    platform2Service.faultDevice(msg.body().toString());
                });
            } else if (platform == 3) {
                invokeRpc((t) -> {
                    phtService.faultDevice(msg.body().toString());
                });
            }
        });

        // 最新数据
        eventBus.consumer("connector.data.latest", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            Integer port = new JsonObject(msg.body().toString()).getInteger("port");
            logger.debug("==>port:" + port + "==>platform:" + platform + "==>" + "currentDate：" + msg.body().toString());
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    if (platform == 1) {
                        invokeRpc((t) -> {
                            platform2Service.data(msg.body().toString());
                        });
                    } else if (platform == 3) {
                        invokeRpc((t) -> {
                            phtService.data(msg.body().toString());
                        });
                    }
                }
            });

        });

        eventBus.consumer("connector.data.status.update", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            JsonObject json = new JsonObject(msg.body().toString());
            if (platform == 1) {
                logger.debug("给平台回复：" + msg.body().toString());
                invokeRpc((t) -> {
                    platform2Service.sendCmd(json.toString());
                });
            } else if (platform == 3) {
                invokeRpc((t) -> {
                    phtService.sendCmd(json.toString());
                });
            }
        });

        eventBus.consumer("connector.equipment.status", msg -> {
            Integer platform = new JsonObject(msg.body().toString()).getInteger("platform");
            if (platform == 1) {
                invokeRpc((t) -> {
                    platform2Service.statusChange(msg.body().toString());
                });
            } else if (platform == 3) {
                invokeRpc((t) -> {
                    phtService.statusChange(msg.body().toString());
                });
            }
        });

//        ReferenceConfig<APPService> reference3 = new ReferenceConfig<>(); // 此实例很重，封装了与注册中心的连接以及与提供者的连接，请自行缓存，否则可能造成内存和连接泄漏
//        reference3.setApplication(application);
//        reference3.setRegistry(registry); // 多个注册中心可以用setRegistries()
//        reference3.setInterface(APPService.class);
//        reference3.setCheck(false);
//        reference3.setTimeout(30000);
//        reference3.setAsync(false);
//        reference3.setVersion("1.0.0");
//        reference3.setFilter("dubboFilter");
//        
//        APPService aPPService =reference3.get();
//        
//        ReferenceConfig<APPService> reference4 = new ReferenceConfig<>(); // 此实例很重，封装了与注册中心的连接以及与提供者的连接，请自行缓存，否则可能造成内存和连接泄漏
//        reference4.setApplication(application);
//        reference4.setRegistry(registry); // 多个注册中心可以用setRegistries()
//        reference4.setInterface(APPService.class);
//        reference4.setCheck(false);
//        reference4.setTimeout(30000);
//        reference4.setAsync(false);
//        reference4.setVersion("2.0.0");
//        reference4.setFilter("dubboFilter");
//        
//        APPService aPPService2 =reference4.get();

        // 设备回复
        eventBus.consumer("device.callback", msg -> {
            JsonObject json = new JsonObject(msg.body().toString());
            String cmd = json.getString("callCmd");
            Integer port = json.getInteger("port");
            Integer hardwareType = json.getInteger("hardwareType");

            String deviceType = json.getString("deviceType");
            String gatewayType = json.getString("gatewayType");
            String content = json.getString("content");
            Integer operati = json.getInteger("operati");

            if (gatewayType != null && gatewayType.equals("ygateway")) {
                json.put("content", content);
                json.put("gatewayType", gatewayType);
                json.put("operati", operati);
            } else {
                String deviceNum = "";
                String dataAdress = "";
                String operationflag = "";
                String hexValue = "";
                Integer iperationCount = 0;
                String flag = "write";
                List<Command> comm;
                Integer channelType = -1;
                if (StringUtils.equals(json.getString("deviceType"), "106")) {
                    deviceNum = cmd.substring(0, 2);
                    operationflag = cmd.substring(2, 4);
                    if (StringUtils.equals(operationflag, "10")) {
                        dataAdress = cmd.substring(4, 8);
                        iperationCount = Integer.parseInt(cmd.substring(8, cmd.length() - 4), 16);
                        flag = "write";
                    } else if (StringUtils.equals(operationflag, "03")) {
                        flag = "read";
                        comm = (List<Command>) readMap.get(deviceNum + port);
                        Map<String, Object> parse = parse(comm, deviceNum, port, dataAdress, hexValue, channelType, cmd, deviceType);
                        dataAdress = parse.get("dataAdress") + "";
                        hexValue = parse.get("hexValue") + "";
                        channelType = Integer.parseInt(parse.get("channelType") + "");
                    }

                } else if (StringUtils.equals(json.getString("deviceType"), "117")) {
                    deviceNum = cmd.substring(4, 6);
                    operationflag = cmd.substring(6, 8);
                    if (StringUtils.equals(operationflag, "10")) {
                        http:
//www.hoteastday.com/a/2184944475959472951?qid=mini015&_1_推荐1
                        dataAdress = cmd.substring(8, 12);
                        iperationCount = Integer.parseInt(cmd.substring(12, cmd.length() - 2), 16);
                        flag = "write";
                    } else if (StringUtils.equals(operationflag, "03")) {
                        flag = "read";
                        comm = (List<Command>) readMap.get(deviceNum + port);
                        Map<String, Object> parse = parse(comm, deviceNum, port, dataAdress, hexValue, channelType, cmd, deviceType);
                        dataAdress = parse.get("dataAdress") + "";
                        hexValue = parse.get("hexValue") + "";
                        channelType = Integer.parseInt(parse.get("channelType") + "");
                    }
                } else {
                    hexValue = cmd;
                }
                json.put("deviceNum", Integer.parseInt(deviceNum,16));
                json.put("dataAdress", dataAdress);
                json.put("value", hexValue);
                json.put("flag", flag);
                json.put("sendCmdR", readMap.get(port + ""));
                json.put("sendCmdW", readMap.get(port + "w"));
                json.put("iperationCount", iperationCount);
                json.put("channelType", channelType);
                json.put("hardwareType", hardwareType);
            }
            logger.debug("app cmd 命令回复：" + json.toString());
            try {
                aPPService.callback(json.toString());
            } catch (Exception e2) {
                logger.error("aPPService-" + e2.getMessage());
            }
            try {
                platform2Service.callback(json.toString());
            } catch (Exception e2) {
                logger.error("platform2Service-" + e2.getMessage());
            }
            try {
                aPPService2.callback(json.toString());
            } catch (Exception e2) {
                logger.error("aPPService2-" + e2.getMessage());
            }

        });

        String paramsByport = null;
        JsonObject params = new JsonObject();

        while (true) {
            if (queue.isEmpty()) {
                logger.debug("队列无数据，端口启动完毕");
                break;
            }
            DelayedList key = queue.poll();

            if (key != null) {
                logger.info(queue.size() + "消费消息：" + key.getId() + ":" + key.getBody());

                if (paramsByport == null) {
                    paramsByport = platform2Service.getParamsByport(new JSONObject().toJSONString());
                    redis.set(YRWGDATA, paramsByport, h -> {

                    });
                    params = new JsonObject(paramsByport);
                }

                Integer dtuType = null;
                Integer hardwareType = null;

                String[] strings = key.getBody().split("_");
                int port = Integer.parseInt(strings[1]);
                int platform = Integer.parseInt(strings[2]);
                if (key.getBody().contains("&")) {
                    dtuType = Integer.parseInt(strings[4]);
                    if (!StringUtils.equals(strings[5], "null")) {
                        hardwareType = Integer.parseInt(strings[5]);
                    }
                }

                JsonObject jsonparams = params.getJsonObject(port + "");
                DeploymentOptions deploymentOptions = new DeploymentOptions().setHa(true)// .setWorker(true)
                        .setConfig(new JsonObject().put("port", port).put("appointPort", port).put("platform", platform)
                                .put("dtuType", dtuType).put("hardwareType", hardwareType)
                                .put("spring.redis.host", env.getProperty("spring.redis.host"))
                                .put("mongoDBAddress", env.getProperty("spring.data.mongodb.uri"))
                                .put("fifteenMinutesFlag", env.getProperty("fifteenMinutesFlag"))
                                .put("jsonparams", jsonparams)
                        );
                vertx.deployVerticle(new CollectorServer(), deploymentOptions, id -> {
                    if (id.succeeded()) {
                        logger.info("Verticle: CollectorServer" + "==>port:" + port + "==>" + id.result() + " deployed!");
                    } else {
                        logger.info("Verticle: CollectorServer" + "==>port:" + port + "==>" + id.cause().getMessage() + " deployed!");
                    }

                });

            }

        }

    }


    public void invokeRpc(Consumer supplier) {
        try {
            supplier.accept("");
        } catch (Exception e) {
            logger.error("invoke rpc error" + e.getMessage());
        }

    }

    public Map<String, Object> parse(List<Command> comm, String deviceNum, Integer port, String dataAdress,
                                     String hexValue, Integer channelType, String cmd, String deviceType) {
        comm = (List<Command>) readMap.get(deviceNum + port);
        dataAdress = comm.get(0).getAddress();
        int index = 0;
        if ("106".equals(deviceType)) {
            index = 6;
        } else if ("117".equals(deviceType)) {
            index = 10;
        }

        for (int i = 0; i < comm.size(); i++) {
            Command command = comm.get(i);
            int byteNum = comm.get(i).getByteNum();
            String type = comm.get(i).getType();
            String data = cmd.substring(index, index = index + byteNum * 4);
            if (command.getSendId().length() >= 5) {
                if (Integer.parseInt(command.getSendId().substring(4)) < 5) {
                    String binary = String.format("%016d",
                            Long.parseLong(Long.toBinaryString(Long.parseLong(data, 16))));
                    int type_106 = Integer.parseInt(binary.substring(0, 3), 2);
                    int value_106 = Integer.parseInt(binary.substring(3), 2);
                    if (type_106 == 0) {
                        hexValue = spitValue(hexValue, value_106);
                        channelType = 0;
                    } else if (type_106 == 1) {
                        hexValue = spitValue(hexValue, value_106);
                        channelType = 1;
                    } else if (type_106 == 2) {
                        hexValue = spitValue(hexValue, value_106 - 3000);
                        channelType = 2;
                    } else if (type_106 == 3) {
                        hexValue = spitValue(hexValue, value_106 / 10);
                        channelType = 3;
                    } else if (type_106 == 4) {
                        hexValue = spitValue(hexValue, value_106 / 10);
                        channelType = 4;
                    }

                }
            } else {

                if (StringUtils.equals(type, "5")) {
                    String binary = String.format("%016d",
                            Long.parseLong(Long.toBinaryString(Long.parseLong(data, 16))));
                    hexValue = spitValue(hexValue, Integer.parseInt(binary.substring(0, 8), 2));
                }
                if (StringUtils.equals(type, "6")) {
                    hexValue = spitValue(hexValue, Integer.parseInt(data, 16));
                } else if (StringUtils.equals(type, "10")) {
                    double cvalue = new BigDecimal(Integer.parseInt(data, 16) / 10).setScale(1).doubleValue();
                    hexValue = spitValue(hexValue, cvalue);
                } else if (StringUtils.equals(type, "11")) {
                    if (data.length() == 12) {
                        hexValue = spitValue(hexValue, data);
                    } else {
                        hexValue = spitValue(hexValue, Integer.parseInt(data, 16));
                    }
                } else if (StringUtils.equals(type, "12")) {
                    Calendar occurTime = Calendar.getInstance();
                    occurTime.set(Calendar.YEAR, 2000 + Integer.parseInt(data.substring(0, 4), 16));
                    occurTime.set(Calendar.MONTH, Integer.parseInt(data.substring(4, 8), 16) - 1);
                    occurTime.set(Calendar.DAY_OF_MONTH, Integer.parseInt(data.substring(8, 12), 16));
                    occurTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(data.substring(12, 16), 16));
                    occurTime.set(Calendar.MINUTE, Integer.parseInt(data.substring(16, 20), 16));
                    occurTime.set(Calendar.SECOND, Integer.parseInt(data.substring(20, 24), 16));
                    occurTime.set(Calendar.MILLISECOND, 0);
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    hexValue = spitValue(hexValue, dateFormat.format(occurTime.getTime()));
                } else if (StringUtils.equals(type, "13")) {
                    hexValue = spitValue(hexValue, Integer.parseInt(data, 16));
                } else if (StringUtils.equals(type, "15")) {
                    hexValue = spitValue(hexValue, Long.parseLong(data, 16) / 10000);
                } else if (StringUtils.equals(type, "17")) {
                    hexValue = spitValue(hexValue, Long.parseLong(data, 16) / 100);
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("hexValue", hexValue);
        map.put("dataAdress", dataAdress);
        map.put("channelType", channelType);
        return map;
    }

    public String spitValue(String value, Object str) {
        if (StringUtils.isEmpty(value)) {
            return str + "";
        } else {
            return value + "~" + str;
        }
    }

    public static class CollectorServiceImpl implements CollectorService {

        @Autowired
        private Environment env;

        private Vertx vertx;

        private EventBus eventBus;

        private RedisClient redis;

        private Platform2Service platform2Service;

        public CollectorServiceImpl(Vertx vertx, EventBus eventBus, RedisClient redis,Platform2Service platform2Service) {
            this.vertx = vertx;
            this.eventBus = eventBus;
            this.redis = redis;
            this.platform2Service = platform2Service;
        }
        @Override
        public void deviceAdd(String s) {
            logger.info("receive deviceAdd msg: " + s);
            JsonObject addConfig = new JsonObject(s);
            String deviceId = addConfig.getString("deviceId");
            Integer platform = addConfig.getInteger("platform");
            Integer appointPort = addConfig.getInteger("appointPort");
            Integer dtuType = addConfig.getInteger("dtuType");
            Integer hardwareType = addConfig.getInteger("hardwareType");
//                            String hubHost = addConfig.getString("hubHost");

            JsonObject jsonparams = new JsonObject();
            if(dtuType==2){
                String paramsByport = null;
                JsonObject params = new JsonObject();
                paramsByport = platform2Service.getParamsByport(new JSONObject().toJSONString());
                redis.set(YRWGDATA, paramsByport, h -> {
                });
                params = new JsonObject(paramsByport);
                jsonparams = params.getJsonObject(appointPort + "");
            }
            DeploymentOptions deploymentOptions = new DeploymentOptions();
            deploymentOptions.setConfig(new JsonObject().put("deviceId", deviceId).put("platform", platform)
                    .put("appointPort", appointPort).put("dtuType", dtuType).put("hardwareType", hardwareType)
                    .put("spring.redis.host", PropertyUtil.getProperty("spring.redis.host"))
                    .put("mongoDBAddress", PropertyUtil.getProperty("spring.data.mongodb.uri"))
                    .put("fifteenMinutesFlag", PropertyUtil.getProperty("fifteenMinutesFlag"))
                    .put("jsonparams", jsonparams));
            vertx.deployVerticle(new CollectorServer(), deploymentOptions, id -> {
                logger.info("Verticle: " + id + " deployed!");
            });
        }
        @Override
        public void setModel(String msg){
            logger.info("receive setModel msg: " + msg);
            JsonObject addConfig = new JsonObject(msg);
            Integer appointPort = addConfig.getInteger("appointPort");
            Integer dtuType = addConfig.getInteger("dtuType");
            if(dtuType==2) {
                String paramsByport = null;
                JsonObject params = new JsonObject();

                paramsByport = platform2Service.getParamsByport(new JSONObject().toJSONString());
                redis.set(YRWGDATA, paramsByport, h -> {
                });
                params = new JsonObject(paramsByport);
                JsonObject jsonparams = params.getJsonObject(appointPort + "");
                vertx.eventBus().publish(Constant.MOD_SEND_SET_MODEL + appointPort, new JsonObject().put("jsonparams", jsonparams));

            }
        }
        @Override
        public void deviceDelete(String s) {
            logger.info("receive deviceDelete msg: " + s);
            JsonObject deleteConfig = new JsonObject(s);
            String deviceId = deleteConfig.getString("deviceId");
            Integer platform = deleteConfig.getInteger("platform");
            int port = deleteConfig.getInteger("port");
            redis.get("port_" + port + "_" + platform, res -> {
                eventBus.publish("connector.delete", new JsonObject().put("deviceId", deviceId).put("platform", platform));
                String[] strings = res.result().split("_");
                vertx.undeploy(strings[0]);
                redis.del("port_" + port + "_" + platform, rlt -> {
                });
                redis.del("port1_" + port + "_map_error", rlt -> {
                });
                redis.del("port1_" + port + "_map_read", rlt -> {
                });
            });
        }

        @Override
        public void readStart(String s) {
            logger.info("receive readStart msg: " + s);
            JsonObject startConfig = new JsonObject(s);
            Integer port = startConfig.getInteger("port");
            Integer platform = startConfig.getInteger("platform");
            String cmd = startConfig.getString("cmd");
            float rate = startConfig.getFloat("rate", 15.0f);
            Integer hardwareType = startConfig.getInteger("hardwareType");
            String did = startConfig.getString("deviceId");
            int ct = startConfig.getInteger("ct", 1);
            int pt = startConfig.getInteger("pt", 1);
            int lct = startConfig.getInteger("lct", 1);
            JsonObject warn = startConfig.getJsonObject("warn");
            if (!startConfig.containsKey("warn")) {
                warn = new JsonObject();
            }
            eventBus.publish("connector.read.start." + port, new JsonObject()
                    .put("port", port)
                    .put("hardware_type", hardwareType)
                    .put("deviceId", did)
                    .put("cmd", cmd)
                    .put("rate", rate)
                    .put("ct", ct)
                    .put("pt", pt)
                    .put("lct", lct)
                    .put("warn", warn)
                    .put("platform", platform)
            );
        }

        @Override
        public void readStop(String s) {
            logger.info("receive readStop msg: " + s);
            JsonObject stopConfig = new JsonObject(s);
            Integer port = stopConfig.getInteger("port");
            Integer platform = stopConfig.getInteger("platform");
            eventBus.publish("connector.read.stop." + port, new JsonObject().put("port", port).put("platform", platform));

/*            redis.get("port_" + port+"_"+platform, res -> {
                vertx.undeploy(res.result());
            });*/
        }

        @Override
        public void errorStart(String s) {
            logger.info("receive errorStart msg: -------------------" + s);
            JsonObject readStartConfig = new JsonObject(s);
            Integer port = readStartConfig.getInteger("port");
            Integer platform = readStartConfig.getInteger("platform");
            Integer hardwareType = readStartConfig.getInteger("hardwareType");
            String did = readStartConfig.getString("deviceId");
            String cmd = readStartConfig.getString("cmd");
            float rate = readStartConfig.getFloat("rate", 15.0f);
            Integer ct = readStartConfig.getInteger("ct", 1);
            Integer pt = readStartConfig.getInteger("pt", 1);
            Integer lct = readStartConfig.getInteger("lct", 1);
            eventBus.send("connector.error.start." + port, new JsonObject()
                    .put("port", port)
                    .put("hardware_type", hardwareType)
                    .put("deviceId", did)
                    .put("cmd", cmd)
                    .put("rate", rate)
                    .put("ct", ct)
                    .put("pt", pt)
                    .put("lct", lct)
                    .put("platform", platform)
            );
        }

        @Override
        public void errorStop(String s) {
            logger.info("receive errorStop msg: " + s);
            JsonObject errorStopConfig = new JsonObject(s);
            Integer port = errorStopConfig.getInteger("port");
            Integer platform = errorStopConfig.getInteger("platform");
            eventBus.publish("connector.error.stop." + port, new JsonObject().put("port", port).put("platform", platform));

/*            redis.get("port_" + port+"_"+platform, res -> {
                vertx.undeploy(res.result());
            });*/
        }

        @Override
        public void readRestart(String s) {

        }

        @Override
        public void errorRestart(String s) {

        }

        @Override
        public void cmd(String s) {
            logger.info("rpc receive cmd msg: " + s);
            JsonObject cmdConfig = new JsonObject(s);
            Integer port = cmdConfig.getInteger("port");
            Integer dtutype = cmdConfig.getInteger("dtutype");
            Integer hardwareType = cmdConfig.getInteger("hardwareType");
            Integer deviceNum = cmdConfig.getInteger("deviceNum");
            String source = cmdConfig.getString("source");
            String gateway = cmdConfig.getString("gatewayType");
            String content = cmdConfig.getString("content");
            Integer operationNum = cmdConfig.getInteger("operationNum");


            String sendCmd = "";
            String devicestr = "";

            if (gateway != null && gateway.equals("ygateway") && dtutype == 2) {

                String len = "";
                String ycmd = "";
                String initcmd = "";

                String binary = "00000001";
                String contro = String.format("%02x", Integer.parseInt(binary, 2));
                devicestr = String.format("%04x", 1);
                String operationNumHex = String.format("%02x", operationNum);

                if (operationNum == 6) {
                    initcmd = Utils.bytes2String(content.getBytes());
                    len = String.format("%04x", content.getBytes().length);

                } else if (operationNum == 5) {
                    len = "0002";
                    initcmd = content;
                } else if (operationNum == 15) {
                    len = String.format("%04x", content.getBytes().length);
                    initcmd = Utils.bytes2String(content.getBytes());
                }
                ycmd = addStr("2B", contro, devicestr, operationNumHex, len, initcmd);
                sendCmd = addStr(ycmd, Utils.checkNumFisrt(ycmd), "16").toUpperCase();

                logger.info("send cmd" + port + "--" + sendCmd);
                eventBus.send("connector.cmd." + port, new JsonObject().put("port", port).put("cmd", sendCmd));
                return;
            }

            if (StringUtils.equals(source, "app")) {
                String sendId = cmdConfig.getString("sendId");
                String value = cmdConfig.getString("value");
                String flag = cmdConfig.getString("flag");
                String deviceType = "";
                if (StringUtils.equals(sendId, "signal")) {
                    sendCmd = "at-usr.cnAT+CSQ\r";
                } else {

                    devicestr = String.format("%02x", deviceNum).toUpperCase();
                    String[] splitAddress = sendId.split("~");
                    String startAddress = splitAddress[0].substring(0, 4);
                    String endAddress = splitAddress[splitAddress.length - 1].substring(0, 4);
                    List<Command> comm = new ArrayList<>();
                    if (hardwareType == 0 || hardwareType == 1 || hardwareType == 31 || hardwareType == 41 || hardwareType == 40) {
                        deviceType = "106";
                        comm = commandMapper.findAllByAddressAll(startAddress, endAddress, deviceType);
                    } else if (hardwareType == 2 || hardwareType == 4 || hardwareType == 42) {
                        deviceType = "117";
                        comm = commandMapper.findAllBySendIdAll(splitAddress[0], splitAddress[splitAddress.length - 1],
                                deviceType);
                    }
                    if (!comm.isEmpty()) {
                        startAddress = comm.get(0).getAddress();
                    } else {
                        logger.info("无此命令");
                        return;
                    }
                    int b = 0;
                    String hexValue = "";
                    if (StringUtils.equals(flag, "write")) {
                        String[] splitValue = value.split("~");
                        for (int i = 0; i < comm.size(); i++) {
                            if (sendId.length() > 4) {
                                b = b + 1;
                                int binaryValue = 0;
                                String binaryType = "";
                                if (StringUtils.equals(splitAddress[i].substring(4), "0")) {
                                    binaryType = Integer.toBinaryString(0);
                                    binaryValue = Integer.parseInt(splitValue[i]);
                                } else if (StringUtils.equals(splitAddress[i].substring(4), "1")) {
                                    binaryType = Integer.toBinaryString(1);
                                    binaryValue = Integer.parseInt(splitValue[i]);
                                } else if (StringUtils.equals(splitAddress[i].substring(4), "2")) {
                                    binaryType = Integer.toBinaryString(2);
                                    binaryValue = Integer.parseInt(splitValue[i]) + 3000;
                                } else if (StringUtils.equals(splitAddress[i].substring(4), "3")) {
                                    binaryType = Integer.toBinaryString(3);
                                    binaryValue = Integer.parseInt(splitValue[i]) * 10;
                                } else if (StringUtils.equals(splitAddress[i].substring(4), "4")) {
                                    binaryType = Integer.toBinaryString(4);
                                    binaryValue = Integer.parseInt(splitValue[i]) * 10;
                                }

                                String v = addStr(String.format("%03d", Long.parseLong(binaryType)),
                                        String.format("%013d", Long.parseLong(Long.toBinaryString(binaryValue))));
                                hexValue = hexValue + String.format("%04x", Integer.valueOf(v, 2));
                            } else {
                                b = b + comm.get(i).getByteNum();
                                String type = comm.get(i).getType();
                                if (StringUtils.equals(type, "5")) {
                                    String v = String.format("%02x",
                                            Integer.parseInt(splitValue[i]));
                                    hexValue = hexValue + v + v;
                                }
                                if (StringUtils.equals(type, "6")) {
                                    hexValue = hexValue + String.format("%04x", Integer.parseInt(splitValue[i]));
                                } else if (StringUtils.equals(type, "10")) {
                                    hexValue = hexValue + String.format("%04x", Integer.parseInt(splitValue[i]) * 10);
                                } else if (StringUtils.equals(type, "11")) {
                                    hexValue = hexValue + splitValue[i];
                                } else if (StringUtils.equals(type, "12")) {
                                    for (String st : splitValue[i].split("-")) {
                                        hexValue = hexValue + String.format("%04x", Integer.parseInt(st));
                                    }
                                } else if (StringUtils.equals(type, "13")) {
                                    Integer len = comm.get(i).getByteNum() * 4;
                                    hexValue = hexValue + String.format("%0" + len + "x", Integer.parseInt(splitValue[i]));
                                } else if (StringUtils.equals(type, "15")) {
                                    Integer len = comm.get(i).getByteNum() * 4;
                                    hexValue = hexValue + String.format("%0" + len + "x", Long.parseLong(splitValue[i]) * 10000);
                                } else if (StringUtils.equals(type, "17")) {
                                    Integer len = comm.get(i).getByteNum() * 4;
                                    hexValue = hexValue + String.format("%0" + len + "x", Long.parseLong(splitValue[i]) * 100);
                                }
                            }
                        }
                    }
                    String byteLength = String.format("%02x", b * 2);
                    String byteNum = String.format("%04x", b);

                    if (deviceType.equals("106")) {
                        if (StringUtils.equals(flag, "write")) {
                            sendCmd = Utils.checkNumSecondAll(
                                    addStr(devicestr + "10", startAddress, byteNum, byteLength, hexValue));
                            readMap.put(port + "w", sendCmd);
                        } else {
                            sendCmd = Utils.checkNumSecondAll(
                                    addStr(devicestr + "03", startAddress, String.format("%04x", comm.stream().mapToInt(Command::getByteNum).sum())));
                            readMap.put(port + "", sendCmd);
                            readMap.put(devicestr + port, comm);
                        }

                    } else if (deviceType.equals("117")) {
                        if (StringUtils.equals(flag, "write")) {
                            sendCmd = "68" + Utils.checkNumFisrtAll(
                                    addStr("F0", devicestr + "10", startAddress, byteNum, byteLength, hexValue));
                            readMap.put(port + "w", sendCmd);
                        } else {
                            sendCmd = "68" + Utils.checkNumFisrtAll(addStr("F0", devicestr + "03", startAddress,
                                    String.format("%04x", comm.stream().mapToInt(Command::getByteNum).sum()) + ""));
                            readMap.put(port + "", sendCmd);
                            readMap.put(devicestr + port, comm);
                        }

                    } else if (dtutype == 0 && hardwareType == 10) {

                    }
                }

                if (!StringUtils.isEmpty(sendCmd)) {
                    if (dtutype == 2 && (deviceType.equals("117") || deviceType.equals("106"))) {
                        String binary = "00000001";
                        String contro = String.format("%02x", Integer.parseInt(binary, 2));
                        devicestr = String.format("%04x", deviceNum);
                        String le = String.format("%04x", sendCmd.length() / 2);
                        String firstLe = String.format("%04x", sendCmd.length() / 2 + 9);
                        String ycmd = addStr("2B", contro, devicestr, "03", firstLe, "02", "01F4", "00002580", le, sendCmd);
                        sendCmd = addStr(ycmd, Utils.checkNumFisrt(ycmd), "16").toUpperCase();
                    }
                    logger.info("send cmd" + port + "--" + sendCmd);
//					if(!mapCmd.containsKey(port)) {
//						Queue<String> queue = new ConcurrentLinkedQueue<>();
//						queue.add(sendCmd);
//						mapCmd.put(port, queue);
//					}else {
//						Queue<String> queue = mapCmd.get(port);
//						queue.add(sendCmd);
//					}
                    eventBus.send("connector.cmd." + port, new JsonObject().put("port", port).put("cmd", sendCmd));
                }

            } else {
                String operation = cmdConfig.getString("operation");
                String cmd = cmdConfig.getString("cmd");
                if (dtutype == 0) {
                    eventBus.send("connector.cmd." + port, new JsonObject().put("port", port).put("cmd", cmd));
                } else if (dtutype == 1) {
                    StringBuilder sb = new StringBuilder();
                    if (deviceNum < 10) {
                        devicestr = "0" + deviceNum;
                    } else {
                        devicestr = deviceNum + "";
                    }
                    if (StringUtils.equals(operation, "clean")) {
                        sb.append(devicestr).append(Constant.CLEAN_106);
                    } else {
                        sb.append(devicestr).append(Constant.RESET_106);
                    }
                    String checkNumSecond = Utils.checkNumSecond(sb.toString());
                    sb.append(checkNumSecond).insert(0, Constant.ZHOGNHUISTART);
                    String checkNumFisrt = Utils.checkNumFisrt(sb.toString());
                    sb.append(checkNumFisrt).append("16");
                    eventBus.send("connector.cmd." + port,
                            new JsonObject().put("port", port).put("cmd", sb.toString()));

                } else if (dtutype == 2) {
                    StringBuilder sb = new StringBuilder();
                    if (deviceNum < 10) {
                        devicestr = "0" + deviceNum;
                    } else {
                        devicestr = deviceNum + "";
                    }
                    if (StringUtils.equals(operation, "clean")) {
                        sb.append(devicestr).append(Constant.CLEAN_106);
                    } else {
                        sb.append(devicestr).append(Constant.RESET_106);
                    }
                    String checkNumSecond = Utils.checkNumSecond(sb.toString());
                    sb.append(checkNumSecond).insert(0, Constant.ZHOGNHUISTART);
                    String checkNumFisrt = Utils.checkNumFisrt(sb.toString());
                    sb.append(checkNumFisrt).append("16");
                    eventBus.send("connector.cmd." + port,
                            new JsonObject().put("port", port).put("cmd", sb.toString()));
                }
            }
        }

        @Override
        public void ping(String s) {
            System.out.println(s);
        }


        @Override
        public void changeDeviceId(String s) {
            logger.info("rpc receive changeDeviceId msg: " + s);
            JsonObject cmdConfig = new JsonObject(s);
            Integer port = cmdConfig.getInteger("port");
            String deviceId = cmdConfig.getString("deviceId");

            eventBus.send("update.deviceId." + port,
                    new JsonObject().put("deviceId", deviceId));

            String readKey = "port1_" + port + "_map_read";
            redis.hset(readKey, "deviceId",
                    deviceId, h -> {
                    });
            String errorKey = "port1_" + port + "_map_error";
            redis.hset(errorKey, "deviceId",
                    deviceId, h -> {
                    });

        }

        public String addStr(String... args) {
            StringBuilder sb = new StringBuilder();
            for (String temp : args) {
                sb.append(temp);
            }
            return sb.toString();
        }

        public String spiltCmd(Integer dtutype, Integer hardwareType, String operation, String devicestr, String cmd) {
            String cmdNew = "";
            if (dtutype == 0 && (hardwareType == 0 || hardwareType == 1)) {
                return spCmd106(devicestr, cmd);
            } else if (dtutype == 0 && hardwareType == 2 || hardwareType == 4) {
                String str = addStr(Constant.DTU_BEFORE_117, devicestr, cmd);
                String checkNumfirst = Utils.checkNumFisrt(str);
                cmdNew = addStr(str, checkNumfirst);
                return cmdNew;
            } else if (dtutype == 0 && hardwareType == 10) {
                devicestr = "03E7";
                String str = addStr(devicestr, cmd);
                String checkNumSecond = Utils.checkNumSecond(str);
                cmdNew = addStr(str, checkNumSecond);
                return cmdNew;
            } else if (dtutype == 1 && hardwareType == 30) {
                String cmd106 = spCmd106(devicestr, cmd);
                String str = addStr(Constant.ZHOGNHUISTART, cmd106);
                String checkNumFisrt = Utils.checkNumFisrt(str);
                cmdNew = addStr(str, checkNumFisrt, "16");
                return cmdNew;

            } else {
                return cmdNew;
            }
        }

        public String spCmd106(String devicestr, String cmd) {
            String str = addStr(devicestr, cmd);
            String checkNumSecond = Utils.checkNumSecond(str);
            String cmdNew = addStr(str, checkNumSecond);
            return cmdNew;
        }

        public String getCmd(Integer dtutype, Integer hardwareType, String operation, String devicestr) {
            String cmdNew = "";
            if (StringUtils.equals(operation, "clean")) {

            } else if (StringUtils.equals(operation, "rest")) {
                addStr(devicestr, Constant.DTU_RESET_106);

            } else if (StringUtils.equals(operation, "check")) {

            } else if (StringUtils.equals(operation, "off")) {

            } else if (StringUtils.equals(operation, "on")) {

            }

            return "";
        }


//		public AddCmd sumCmd(String address, String value,Command comm) {
//			int binaryValue = 0;
//			String binaryType = "";
//			if (StringUtils.equals(splitAddress[i].substring(4), "0")) {
//				binaryType = Integer.toBinaryString(0);
//				binaryValue = Integer.parseInt(splitValue[i]);
//			} else if (StringUtils.equals(splitAddress[i].substring(4), "1")) {
//				binaryType = Integer.toBinaryString(1);
//				binaryValue = Integer.parseInt(splitValue[i]);
//			} else if (StringUtils.equals(splitAddress[i].substring(4), "2")) {
//				binaryType = Integer.toBinaryString(2);
//				binaryValue = Integer.parseInt(splitValue[i]) + 3000;
//			} else if (StringUtils.equals(splitAddress[i].substring(4), "3")) {
//				binaryType = Integer.toBinaryString(3);
//				binaryValue = Integer.parseInt(splitValue[i]) * 10;
//			} else if (StringUtils.equals(splitAddress[i].substring(4), "4")) {
//				binaryType = Integer.toBinaryString(4);
//				binaryValue = Integer.parseInt(splitValue[i]) * 10;
//			}
//			hexValue = hexValue + Integer.valueOf(addStr(String.format("%04s", binaryType),
//					String.format("%012s", Integer.toBinaryString(binaryValue))), 2);
//		} else {
//			b = b + comm.get(i).getByteNum();
//			if (StringUtils.equals(comm.get(i).getMainType(), "6")) {
//				hexValue = hexValue + Integer.toHexString(Integer.parseInt(splitValue[i]));
//			} else if (StringUtils.equals(comm.get(i).getMainType(), "10")) {
//				hexValue = hexValue + Integer.toHexString(Integer.parseInt(splitValue[i]) * 10);
//			} else if (StringUtils.equals(comm.get(i).getMainType(), "11")) {
//				hexValue = hexValue + Integer.toHexString(Integer.parseInt(splitValue[i]));
//			} else if (StringUtils.equals(comm.get(i).getMainType(), "12")) {
//				for (String st : splitValue[i].split("-")) {
//					hexValue = hexValue + Integer.toHexString(Integer.parseInt(st));
//				}
//			} else if (StringUtils.equals(comm.get(i).getMainType(), "13")) {
//				hexValue = hexValue + String.format("%04x", Integer.parseInt(splitValue[i]));
//			}
//		}
//			String byteNum=String.format("%02x", b * 2);
//			String byteLength=String.format("%04x", b);
//			AddCmd addCmd = new AddCmd();
//			addCmd.setHexValue(hexValue);
//			addCmd.setB(b);
//			addCmd.setByteLength(byteLength);
//			addCmd.setByteNum(byteNum);
//			return addCmd;
//		}

    }

}


